<?php
namespace App\Http\Middleware;

use App\Exceptions\BusinessException;
use App\Models\Admin\UserAccessModel;
use App\Services\UserService;
use Closure;
use Illuminate\Foundation\Validation\ValidatesRequests;

class AppCheckTokenMiddle
{
    use ValidatesRequests;

    /**
     * Handle an incoming request.
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws BusinessException
     */
    public function handle($request, Closure $next)
    {
        $rule = [
            'token' => 'required|string'
        ];
        $this->validate($request, $rule);
        $user_access = UserAccessModel::query()->where('token', '=' , $request->token)->first();
        if (!empty($user_access) && $user_access->getAttribute('effective_time') > time()) {
            $user = $user_access->getAttribute('content');
            UserService::auth(json_decode($user, true));
            return $next($request);
        }
        throw new BusinessException('Invalid token', 10001);
    }
}